package edu.uwm.cs552;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;

public class RailDraw implements HexBoardEditAction {
	private final RailState rail;
	private final Player player;
	private ImageIcon[] icons;

	public RailDraw(RailState r, Player p) {
		rail = r;
		player = p;
	}
	
	public RailState getRail() {
		return rail;
	}
	
	public void apply(HexBoard hexBoard, Point p, double scale, double bound) {
		HexEdge h = HexEdge.fromPoint(p, scale, bound);
		if (h != null) {
			if (rail == null) hexBoard.removeRail(player, h);
			else hexBoard.putRail(player, h,rail);
		}
	}
	
	public String getLabel() {
		return rail == null ? "Clear Build" : "Build Track";
	}

	public ImageIcon getIcon() {
		int i = rail == null ? RailState.values().length : rail.ordinal();
		return getRailIcons(player != null ? player.getPlayerColor() : Color.BLACK)[i];
	}

	/**
	 * Return the (singleton) array of icons for terrains indexed by terrain ordinal.
	 * With one extra item at the end for blank icon.
	 * @return
	 */
	private ImageIcon[] getRailIcons(Color c) {
		if (icons == null) {
			ImageIcon[] result = new ImageIcon[RailState.values().length+1];
			for (int i=0; i < result.length; ++i) {
				BufferedImage im = new BufferedImage(ICON_SIZE,ICON_SIZE, BufferedImage.TYPE_INT_ARGB);
				Graphics g = im.getGraphics();
				g.translate(0, ICON_SIZE/2);
				if (i < RailState.values().length) {
					g.setColor(c);
					RailState.values()[i].draw((Graphics2D)g, HexEdge.ORIGIN, ICON_SIZE);
				}
				result[i] = new ImageIcon(im);
			}
			icons = result;
		}
		return icons;
	}

}
